package p.ithorns.support.arthas;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicBoolean;

@RestController
@RequestMapping
public class LogEmitter {
    @GetMapping(value = "/log/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseBodyEmitter streamLogs() {
        // 异步任务标志位
        AtomicBoolean running = new AtomicBoolean(true);

        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        // 开启异步线程处理数据并发送
        Thread thread = new Thread(() -> {
            try {
                while (true) {
                    String logEntry = getLatestLogEntry();
                    if (logEntry != null) {
                        emitter.send("data: " + logEntry, MediaType.TEXT_EVENT_STREAM);
                    }
                    // 每秒检查一次日志更新
                    Thread.sleep(2000);
                }
            } catch (Exception e) {
                // 出现异常时结束响应并传递错误信息
                emitter.completeWithError(e);
            }
        });

        thread.start();

        // 监听客户端断开连接
        emitter.onCompletion(() -> {
            running.set(false); // 停止线程
            thread.interrupt(); // 中断线程
        });

        emitter.onTimeout(() -> {
            running.set(false);
            thread.interrupt();
            emitter.complete();
        });

        return emitter;
    }
    private String getLatestLogEntry() {
        // 模拟从日志文件中获取最新日志条目
        return LocalDateTime.now() +  " - INFO: User logged in successfully.\r\n";
    }

}